package org.example.controller;

import org.example.exception.AppException;
import org.example.model.Article;
import org.example.model.User;
import org.example.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private List<Article> articleList;

    @GetMapping("/init")
    public Object init(HttpServletRequest request){
        Map<String, Object> data = new HashMap<>();
        //获取用户信息
        HttpSession session = request.getSession(false);
        if(session != null){
            User user = (User) session.getAttribute("user");
            if(user != null)
                data.put("user", user);
        }
        //从数据库查询所有文章数据
        List<Article> articles = articleService.queryAll();
        data.put("articleList", articles);
        return data;//ok=true, data={user:{}, articleList:[{id:1}]}
    }

    @GetMapping("/personal")
    public Object personal(HttpSession session){
        //根据登录用户（session获取，不用前端传）查询关联文章列表，并返回
        User user = (User) session.getAttribute("user");
        List<Article> list = articleService.queryByUserId(user.getId());
        return list;
    }

    @GetMapping("/detail")
    public Object detail(Integer id){
        //根据文章id查询一个文章
        Article a = articleService.queryById(id);
        if(a == null)
            throw new AppException("找不到该文章："+id);
        return a;
    }

    @PostMapping("/add")
    public Object add(@RequestBody Article a,
                      HttpSession session){//title,content,没有id
        //添加一个文章：需要插入标题，内容，userid（从session获取）
        User user = (User) session.getAttribute("user");
        //数据库可以使用insertSelective已生成的方法
        a.setUserId(user.getId());
        int n = articleService.insert(a);
        return null;
    }

    @PostMapping("/update")
    public Object update(@RequestBody Article a){//id，title，content
        int n = articleService.update(a);
        if(n <= 0)
            throw new AppException("修改失败，没有该文章："+a.getId());
        return null;
    }

    @GetMapping("/delete")
    public Object delete(int id){
        int n = articleService.delete(id);
        if(n <= 0)
            throw new AppException("删除失败，没有该文章："+id);
        return null;
    }
}
